<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MyRedux Test</title>
  </head>
  <body>
    <button id="increment">+1</button>
    <span id="box">0</span>
    <button id="decrement">-1</button>
    <script src="./myRedux.js"></script>
    <script src="./middlewares/logger.js"></script>
    <script src="./middlewares/thunk.js"></script>
    <script>
      // 对 dispatch 进行增强
      function enhancer(createStore) {
        return function (reducer, preLoadedState) {
          const store = createStore(reducer, preLoadedState)
          const dispatch = store.dispatch
          function _dispatch(action) {
            // 如果 action 是一个对象，我们就使用原有的 dispatch
            // 如果是一个函数，我们就调用这个函数并将 dispacth 传入
            if (typeof action === 'function') {
              return action(dispatch)
            }
            dispatch(action)
          }
          return {
            ...store,
            dispatch: _dispatch,
          }
        }
      }

      function counterReducer(state, action) {
        switch (action.type) {
          case 'increment':
            return state + 1
          case 'decrement':
            return state - 1
          default:
            return state
        }
      }
      const rootReducer = combineReducers({counter: counterReducer})
      // const store = createStore(reducer, 0, enhancer)
      const store = createStore(rootReducer, {counter: 0}, applyMiddleware(logger, thunk))
      function increment() {
        return { type: 'increment' }
      }

      function decrement() {
        return { type: 'decrement' }
      }
      const actions = bindActionCreators(
        { increment, decrement },
        store.dispatch
      )
      store.subscribe(() => {
        // 更新视图
        document.getElementById('box').innerHTML = store.getState().counter
      })
      // 获取加按钮，让数值加一
      document.getElementById('increment').onclick = function () {
        // store.dispatch({ type: "increment" })
        // store.dispatch(dispatch => {
        //   setTimeout(() => {
        //     dispatch({ type: "increment" })
        //   }, 1000)
        // })
        actions.increment()
      }
      // 获取减按钮，让数值减一
      document.getElementById('decrement').onclick = function () {
        // store.dispatch({ type: "decrement" })
        actions.decrement()
      }
    </script>
  </body>
</html>
